package com.software.sqlite.utils;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.Session;
import com.software.sqlite.entity.SonicWallEntity;
import com.software.sqlite.entity.SonicwallAccountEntity;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@Slf4j
public class SSHCommUtils {

    /**
     * 测试程序
     * @param args
     */
    public static void main(String[] args) {
        //设备v1.0
//        String res10=
//                "Account Name  Password  Enabled  Comment         Created                   Account Expires           Session Expires   Session Lifetime  Idle Timeout\n" +
//                "zyss664       cawredro  Yes      Auto-Generated  SAT APR 01 19:29:05 2023  SUN MAR 31 19:29:05 2024  30 Days 16:24:00  31 Days           5 Minutes\n" +
//                "zyss711       brodewag  Yes      Auto-Generated  SAT APR 01 19:29:05 2023  SUN MAR 31 19:29:05 2024  30 Days 04:11:00  31 Days           5 Minutes\n" +
//                "zyss537       racowoko  Yes      Auto-Generated  SAT APR 01 19:29:05 2023  SUN MAR 31 19:29:05 2024  30 Days 23:06:00  31 Days           5 Minutes\n" +
//                "zyss10        cheswoch  Yes      Auto-Generated  SAT APR 01 19:29:05 2023  SUN MAR 31 19:29:05 2024  30 Days 17:56:00  31 Days           5 Minutes\n" +
//                "zyss898       stiphomi  Yes      Auto-Generated  SAT APR 01 19:29:05 2023  SUN MAR 31 19:29:05 2024  28 Days 03:18:00  31 Days           5 Minutes\n" +
//                "zyss949       jegokero  Yes      Auto-Generated  SAT APR 01 19:29:05 2023  SUN MAR 31 19:29:05 2024  30 Days 10:09:00  31 Days           5 Minutes\n" +
//                "zyss174       friuephi  Yes      Auto-Generated  SAT APR 01 19:29:05 2023  SUN MAR 31 19:29:05 2024  31 Days           31 Days           5 Minutes\n" +
//                "zyss1668      dititago  Yes      Auto-Generated  SAT APR 01 19:29:05 2023  SUN MAR 31 19:29:05 2024  30 Days 18:14:00  31 Days           5 Minutes\n" +
//                "zyss1902      wapedras  Yes      Auto-Generated  SAT APR 01 19:29:05 2023  SUN MAR 31 19:29:05 2024  27 Days 18:47:00  31 Days           5 Minutes\n" +
//                "zyss954       jiwalibo  Yes      Auto-Generated  SAT APR 01 19:29:05 2023  SUN MAR 31 19:29:05 2024  30 Days 14:45:00  31 Days           5 Minutes\n" +
//                "zyss1699      mipachap  Yes      Auto-Generated  SAT APR 01 19:29:05 2023  SUN MAR 31 19:29:05 2024  30 Days 08:15:00  31 Days           5 Minutes\n" +
//                "zyss475       wriswiso  Yes      Auto-Generated  SAT APR 01 19:29:05 2023  SUN MAR 31 19:29:05 2024  30 Days 04:50:00  31 Days           5 Minutes\n" +
//                "zyss1807      sohesweh  Yes      Auto-Generated  SAT APR 01 19:29:05 2023  SUN MAR 31 19:29:05 2024  30 Days 08:44:00  31 Days           5 Minutes\n" +
//                "zyss1410      slaslasw  Yes      Auto-Generated  SAT APR 01 19:29:05 2023  SUN MAR 31 19:29:05 2024  28 Days 15:16:00  31 Days           5 Minutes\n" +
//                "zyss1427      stabresw  Yes      Auto-Generated  SAT APR 01 19:29:05 2023  SUN MAR 31 19:29:05 2024  29 Days 20:56:00  31 Days           5 Minutes\n" +
//                "zyss1810      wracrafr  Yes      Auto-Generated  SAT APR 01 19:29:05 2023  SUN MAR 31 19:29:05 2024  30 Days 17:41:00  31 Days           5 Minutes\n" +
//                "htgx          miuiwrad  Yes      Auto-Generated  SUN AUG 09 20:41:29 2020  SAT MAR 30 19:26:54 2024  29 Days 08:24:00  31 Days           10 Minutes\n" +
//                "\n";
//        List<SonicwallAccountEntity> accountList=analysisSonicWallAccountV10(res10,1L,"192.168.168.168",22,"admin","12345678",0L,"111");
//        log.info(JSON.toJSONString(accountList));

        //设备v2.0
//        String res="Account Name  UUID                                  Password      Enabled  Comment         Created                   Account Expires           Account Left Lifetime  Session Expires  Session Lifetime  Idle Timeout  Receive Limit  Transmit Limit  Quota Cycle  \n" +
//                "test0001      00000000-0000-0001-0500-2cb8eda0d970  1234abcd      Yes      Auto-Generated  Wed Oct 11 02:04:42 2023  Tue Oct 15 01:37:51 2024  340 Days 00:34:02      30 Days          30 Days           10 Minutes    4000 MB        4000 MB         Per Month    \n" +
//                "test0002      00000000-0000-0002-0500-2cb8eda0d970  1234abcd      Yes      Auto-Generated  Fri Oct 13 01:52:39 2023  Sat Dec  9 21:38:09 2023  29 Days 20:34:20       30 Days          30 Days           10 Minutes    4900 MB        5300 MB         Per Month    \n" +
//                "test0005      00000000-0000-0005-0500-2cb8eda0d970  1234abcd      Yes      Auto-Generated  Thu Nov  9 21:51:04 2023  Sat Dec  9 21:51:04 2023  29 Days 20:47:15       30 Days          30 Days           10 Minutes    4900 MB        Unlimited       Per Month    \n" +
//                "test0004      00000000-0000-0004-0500-2cb8eda0d970  1234abcd      Yes      Auto-Generated  Mon Oct 16 00:55:19 2023  Tue Oct 15 01:49:02 2024  340 Days 00:45:13      30 Days          30 Days           10 Minutes    5400 MB        5300 MB         Per Month    \n" +
//                "test0003      00000000-0000-0006-0500-2cb8eda0d970  1234abcd      Yes      Auto-Generated  Thu Nov  9 21:57:47 2023  Sat Dec  9 21:57:47 2023  29 Days 20:53:58       30 Days          30 Days           10 Minutes    1024 MB        Unlimited       Per Month    \n" +
//                "test0006      00000000-0000-0007-0500-2cb8eda0d970  1234abcddddd  Yes      Auto-Generated  Fri Nov 10 00:23:01 2023  Sun Dec 10 00:23:01 2023  29 Days 23:19:12       30 Days          30 Days           10 Minutes    1024 MB        Unlimited       Per Month    \n" +
//                "config";
//        List<SonicwallAccountEntity> accountList=analysisSonicWallAccountV20(res,1L,"192.168.168.168",22,"admin","12345678");
//        log.info(JSON.toJSONString(accountList));

        //封装调试
//        SonicWallEntity sonicWall=new SonicWallEntity();
//        sonicWall.setSonicwallId(1L);
//        sonicWall.setRemoteIp("192.168.168.168");
//        sonicWall.setRemotePort(22);
//        sonicWall.setRemoteUserName("admin");
//        sonicWall.setRemotePassword("12345678");
//        sonicWall.setUser("test0007");
//        sonicWall.setPassword("1234abcddddd");
//        sonicWall.setReceiveData(1024);
//        sonicWall.setTransmitData(900);
//        sonicWall.setQuotaCycle("month");
//        sonicWall.setSessionLifetime(32);
//        sonicWall.setAccountLifetime(365);
//        String[] result=SSHCommUtils.execSonicWall(sonicWall);
//        String res=result[result.length-1];
//        if(res.contains("Error") || res.contains("changes and return to the previous mode"))
//        {
//            log.info("充值失败");
//        }else{
//            log.info("充值成功");
//        }
          //调试
        String ip = "192.168.168.168";
        int port = 22;
        String localIp = null;
        int localPort = 0;
        int timeOut = 3000;
        String userName = "admin";
        String password = "12345678";
        String[] cmds = new String[] { "configure\n",
                "yes\n",
//                "show user guest detail\n",
                "user guest\n",
                "user test0012 password 1234abcd\n",
                "limit receive 5400\n",
                "limit transmit 5300\n",
//                "quota-cycle month\n",
                "session-lifetime days 30\n",
                "session-lifetime 30 days\n",
                "account-lifetime days 365\n",
                "account-lifetime 365 days\n",
                "commit\n",
                "exit\n",
                "exit\n",
                "exit\n",
                "exit\n"
        };
        String[] result = null;
        try {
            result = execShellCmdBySSH(0L , ip, port, localIp, localPort, timeOut, userName, password, cmds);
            String res=result[result.length-5];
            log.info("==============================="+res);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (result != null) {
            for (String string : result) {
                System.out.println(string);
                System.out.println("-------------------");
            }
        }

    }

    /**
     * sonicwall exec
     * @param sonicWall
     * @return
     */
    public static List<SonicwallAccountEntity> getAccountListByExec(SonicWallEntity sonicWall)
    {
        List<SonicwallAccountEntity> accountList=new ArrayList<>();
        List<String> cmdList=new LinkedList<>();
        cmdList.add("configure\n");
        cmdList.add("yes\n");
        cmdList.add("show user guest detail users\n");
        cmdList.add("show user guest detail\n");
        cmdList.add("commit\n");
        cmdList.add("exit\n");
        String[] cmds =cmdList.toArray(new String[cmdList.size()]);
        try {
            int timeOut = 3000;
            String[] result = execShellCmdBySSH(sonicWall.getSonicwallId(),sonicWall.getRemoteIp(), sonicWall.getRemotePort(), null, 0, timeOut, sonicWall.getRemoteUserName(), sonicWall.getRemotePassword(), cmds);
            if(result!=null && result.length==5){
                String accountResult=result[2];
                if(!accountResult.contains("Error"))
                {
                    accountList=analysisSonicWallAccountV10(accountResult,sonicWall.getSonicwallId(),
                            sonicWall.getRemoteIp(), sonicWall.getRemotePort(),
                            sonicWall.getRemoteUserName(),sonicWall.getRemotePassword(),
                            sonicWall.getShipId(),sonicWall.getShipName());
                }else{
                    accountResult=result[3];
                    if(!accountResult.contains("Error")){
                        accountList=analysisSonicWallAccountV20(accountResult,sonicWall.getSonicwallId(),
                                sonicWall.getRemoteIp(), sonicWall.getRemotePort(),
                                sonicWall.getRemoteUserName(),sonicWall.getRemotePassword(),
                                sonicWall.getShipId(),sonicWall.getShipName());
                    }else{
                        log.error("show user guest detail get Error!!!");
                    }
                }
            }
        } catch (Exception e) {
            log.error(sonicWall.getRemoteIp()+":"+sonicWall.getRemotePort()+" connect ssh error!"+e.getMessage());
            accountList=null;
        }
        return accountList;
    }

    /**
     * sonicwall exec
     * @param sonicWall
     * @return
     */
    public static String[] execSonicWall(SonicWallEntity sonicWall)
    {
        List<String> cmdList=new LinkedList<>();
        cmdList.add("configure\n");
        cmdList.add("yes\n");
        cmdList.add("user guest\n");
        if(CommonUtils.isNotBlank(sonicWall.getUser()) && CommonUtils.isNotBlank(sonicWall.getPassword()))
        {
            cmdList.add("user "+sonicWall.getUser()+" password "+sonicWall.getPassword()+"\n");
        }
        if(sonicWall.getReceiveData()!=null){
            cmdList.add("limit receive "+sonicWall.getReceiveData()+"\n");
        }
        if(sonicWall.getReceiveData()!=null){
            cmdList.add("limit transmit "+sonicWall.getTransmitData()+"\n");
        }
        if(sonicWall.getQuotaCycle()!=null && sonicWall.getQuotaCycle().equals("month")){
            cmdList.add("quota-cycle month\n");
        }
        if(sonicWall.getSessionLifetime()!=null){
            cmdList.add("session-lifetime days "+sonicWall.getSessionLifetime()+"\n");
            cmdList.add("session-lifetime "+sonicWall.getSessionLifetime()+" days\n");
        }
        if(sonicWall.getAccountLifetime()!=null){
            cmdList.add("account-lifetime days "+sonicWall.getSessionLifetime()+"\n");
            cmdList.add("account-lifetime "+sonicWall.getSessionLifetime()+" days\n");
        }
        cmdList.add("commit\n");
        cmdList.add("exit\n");
        cmdList.add("exit\n");
        cmdList.add("exit\n");
        cmdList.add("exit\n");
        String[] cmds =cmdList.toArray(new String[cmdList.size()]);
        String[] result = null;
        try {
            int timeOut = 3000;
            result = execShellCmdBySSH(sonicWall.getSonicwallId(),sonicWall.getRemoteIp(), sonicWall.getRemotePort(), null, 0, timeOut, sonicWall.getRemoteUserName(), sonicWall.getRemotePassword(), cmds);
        } catch (Exception e) {
            log.error(sonicWall.getRemoteIp()+":"+sonicWall.getRemotePort()+" connect ssh error!"+e.getMessage());
        }
        return result;
    }

    /**
     * 使用SSH协议，连接到Linux Shell，执行脚本命令，并获取结果
     *
     * @param dstIp
     * @param dstport
     *            default :22
     * @param localIp
     * @param localPort
     * @param timeOut
     * @param userName
     * @param password
     * @param cmds
     * @return
     * @throws Exception
     */
    public static String[] execShellCmdBySSH(Long sonicWallId,String dstIp, int dstport,
                                             String localIp, int localPort, int timeOut, String userName,
                                             String password, String... cmds)throws Exception {
        Session session = null;
        Channel channel = null;
        InputStream is = null;
        OutputStream os = null;
        String[] result=null;
        try {
            session = JSCHUtils.createSession(dstIp, dstport, localIp,
                    localPort, userName, password, timeOut);
            channel = session.openChannel("shell");

            channel.connect();
            is = channel.getInputStream();
            os = channel.getOutputStream();
            result = new String[cmds.length];
            for (int i = 0; i < cmds.length; i++) {
                String cmd=cmds[i];
                String res=sendCommand(is, os, cmd);
                log.info("cmd--"+cmd+";res--"+res);
                result[i] =res;
            }
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if(is!=null){
                    is.close();
                }
                if(os!=null){
                    os.close();
                }
            } catch (IOException e) {}
            if(channel!=null)
            {
                channel.disconnect();
            }
            if(session!=null)
            {
                session.disconnect();
            }
        }
        return result;
    }

    /**
     * sonicwall v1.0 设备
     * @param result
     * @param sonicWallId
     * @param remoteIp
     * @param remotePort
     * @param remoteUserName
     * @param remotePassword
     * @return
     */
    public static List<SonicwallAccountEntity> analysisSonicWallAccountV10(String result,Long sonicWallId,
                                                                       String remoteIp,Integer remotePort,
                                                                       String remoteUserName,String remotePassword,
                                                                       Long shipId,String shipName)
    {
        List<SonicwallAccountEntity> accountList=new ArrayList<>();
        try {
            result=result.substring(result.indexOf("Account Name"),result.length());
            String[] array=result.split("\n");
            if(array.length>0){
                String title=array[0];
                int AccountNameIndex=0;
                int totalLength=title.length();
                int PasswordIndex=title.indexOf("Password");
                int EnabledIndex=title.indexOf("Enabled");
                int CommentIndex=title.indexOf("Comment");
                int CreatedIndex=title.indexOf("Created");
                int AccountExpiresIndex=title.indexOf("Account Expires");
                int SessionExpiresIndex=title.indexOf("Session Expires");
                int SessionLifetimeIndex=title.indexOf("Session Lifetime");
                int IdleTimeoutIndex=title.indexOf("Idle Timeout");
                for(int k=1;k<array.length;k++){
                    String acc=array[k];
                    System.out.println(acc.length());
                    String accountName=acc.substring(AccountNameIndex,PasswordIndex);
                    accountName=accountName.trim();

                    String pwd=acc.substring(PasswordIndex,EnabledIndex);
                    pwd=pwd.trim();

                    String enabled=acc.substring(EnabledIndex,CommentIndex);
                    enabled=enabled.trim();

                    String comment=acc.substring(CommentIndex,CreatedIndex);
                    comment=comment.trim();

                    String created=acc.substring(CreatedIndex,AccountExpiresIndex);
                    created=created.trim();
                    Date createdTime=DateUtils.parseByDateObjectToString(created);

                    String accountExpires=acc.substring(AccountExpiresIndex,SessionExpiresIndex);
                    accountExpires=accountExpires.trim();
                    Date accountExpiresTime=DateUtils.parseByDateObjectToString(accountExpires);

                    String sessionExpires=acc.substring(SessionExpiresIndex,SessionLifetimeIndex);
                    sessionExpires=sessionExpires.trim();

                    String sessionLifetime=acc.substring(SessionLifetimeIndex,IdleTimeoutIndex);
                    sessionLifetime=sessionLifetime.trim();

                    String idleTimeout=acc.substring(IdleTimeoutIndex,acc.length());
                    idleTimeout=idleTimeout.trim();

                    SonicwallAccountEntity accountModel=new SonicwallAccountEntity();
                    accountModel.setShipId(shipId);
                    accountModel.setShipName(shipName);
                    accountModel.setSonicwallId(sonicWallId);
                    accountModel.setRemoteIp(remoteIp);
                    accountModel.setRemotePort(remotePort);
                    accountModel.setRemoteUserName(remoteUserName);
                    accountModel.setRemotePassword(remotePassword);
                    accountModel.setAccountName(accountName);
                    accountModel.setUuid("");
                    accountModel.setPassword(pwd);
                    accountModel.setEnabled(enabled);
                    accountModel.setComment(comment);
                    accountModel.setCreated(created);
                    accountModel.setCreatedTime(createdTime);
                    accountModel.setAccountExpires(accountExpires);
                    accountModel.setAccountExpiresTime(accountExpiresTime);
                    accountModel.setAccountLeftLifetime("");
                    accountModel.setSessionExpires(sessionExpires);
                    accountModel.setSessionLifetime(sessionLifetime);
                    accountModel.setIdleTimeout(idleTimeout);
                    accountModel.setReceiveLimit("");
                    accountModel.setTransmitLimit("");
                    accountModel.setQuotaCycle("");
                    accountModel.setUseStatus("normal");
                    accountModel.setCreateAdminId(0L);
                    accountModel.setCreateTime(new Date());
                    accountModel.setUpdateAdminId(0L);
                    accountModel.setUpdateTime(new Date());
                    accountList.add(accountModel);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return accountList;
    }

    /**
     * sonicwall v2.0 设备
     * @param result
     * @param sonicWallId
     * @param remoteIp
     * @param remotePort
     * @param remoteUserName
     * @param remotePassword
     * @return
     */
    public static List<SonicwallAccountEntity> analysisSonicWallAccountV20(String result,Long sonicWallId,
                                                                       String remoteIp,Integer remotePort,
                                                                       String remoteUserName,String remotePassword,
                                                                       Long shipId,String shipName)
    {
        List<SonicwallAccountEntity> accountList=new ArrayList<>();
        try {
            result=result.substring(result.indexOf("Account Name"),result.indexOf("config"));
            String[] array=result.split("\n");
            if(array.length>0){
                String title=array[0];
                int AccountNameIndex=0;
                int totalLength=title.length();
                int UUIDIndex=title.indexOf("UUID");
                int PasswordIndex=title.indexOf("Password");
                int EnabledIndex=title.indexOf("Enabled");
                int CommentIndex=title.indexOf("Comment");
                int CreatedIndex=title.indexOf("Created");
                int AccountExpiresIndex=title.indexOf("Account Expires");
                int AccountLeftLifetimeIndex=title.indexOf("Account Left Lifetime");
                int SessionExpiresIndex=title.indexOf("Session Expires");
                int SessionLifetimeIndex=title.indexOf("Session Lifetime");
                int IdleTimeoutIndex=title.indexOf("Idle Timeout");
                int ReceiveLimitIndex=title.indexOf("Receive Limit");
                int TransmitLimitIndex=title.indexOf("Transmit Limit");
                int QuotaCycleIndex=title.indexOf("Quota Cycle");
                for(int k=1;k<array.length;k++){
                    String acc=array[k];
                    String accountName=acc.substring(AccountNameIndex,UUIDIndex);
                    accountName=accountName.trim();
                    String uuid=acc.substring(UUIDIndex,PasswordIndex);
                    uuid=uuid.trim();
                    String pwd=acc.substring(PasswordIndex,EnabledIndex);
                    pwd=pwd.trim();
                    String enabled=acc.substring(EnabledIndex,CommentIndex);
                    enabled=enabled.trim();
                    String comment=acc.substring(CommentIndex,CreatedIndex);
                    comment=comment.trim();
                    String created=acc.substring(CreatedIndex,AccountExpiresIndex);
                    created=created.trim();
                    Date createdTime=DateUtils.parseByDateObjectToString(created);
                    String accountExpires=acc.substring(AccountExpiresIndex,AccountLeftLifetimeIndex);
                    accountExpires=accountExpires.trim();
                    Date accountExpiresTime=DateUtils.parseByDateObjectToString(accountExpires);
                    String accountLeftLifetime=acc.substring(AccountLeftLifetimeIndex,SessionExpiresIndex);
                    accountLeftLifetime=accountLeftLifetime.trim();
                    String sessionExpires=acc.substring(SessionExpiresIndex,SessionLifetimeIndex);
                    sessionExpires=sessionExpires.trim();
                    String sessionLifetime=acc.substring(SessionLifetimeIndex,IdleTimeoutIndex);
                    sessionLifetime=sessionLifetime.trim();
                    String idleTimeout=acc.substring(IdleTimeoutIndex,ReceiveLimitIndex);
                    idleTimeout=idleTimeout.trim();
                    String receiveLimit=acc.substring(ReceiveLimitIndex,TransmitLimitIndex);
                    receiveLimit=receiveLimit.trim();
                    String transmitLimit=acc.substring(TransmitLimitIndex,QuotaCycleIndex);
                    transmitLimit=transmitLimit.trim();
                    String quotaCycle=acc.substring(QuotaCycleIndex,totalLength);
                    quotaCycle=quotaCycle.trim();

                    SonicwallAccountEntity accountModel=new SonicwallAccountEntity();
                    accountModel.setShipId(shipId);
                    accountModel.setShipName(shipName);
                    accountModel.setSonicwallId(sonicWallId);
                    accountModel.setRemoteIp(remoteIp);
                    accountModel.setRemotePort(remotePort);
                    accountModel.setRemoteUserName(remoteUserName);
                    accountModel.setRemotePassword(remotePassword);
                    accountModel.setAccountName(accountName);
                    accountModel.setUuid(uuid);
                    accountModel.setPassword(pwd);
                    accountModel.setEnabled(enabled);
                    accountModel.setComment(comment);
                    accountModel.setCreated(created);
                    accountModel.setCreatedTime(createdTime);
                    accountModel.setAccountExpires(accountExpires);
                    accountModel.setAccountExpiresTime(accountExpiresTime);
                    accountModel.setAccountLeftLifetime(accountLeftLifetime);
                    accountModel.setSessionExpires(sessionExpires);
                    accountModel.setSessionLifetime(sessionLifetime);
                    accountModel.setIdleTimeout(idleTimeout);
                    accountModel.setReceiveLimit(receiveLimit);
                    accountModel.setTransmitLimit(transmitLimit);
                    accountModel.setQuotaCycle(quotaCycle);
                    accountModel.setUseStatus("normal");
                    accountModel.setCreateAdminId(0L);
                    accountModel.setCreateTime(new Date());
                    accountModel.setUpdateAdminId(0L);
                    accountModel.setUpdateTime(new Date());
                    accountList.add(accountModel);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return accountList;
    }

    /**
     * 执行Shell命令，并获取执行结果
     *
     * @param is
     * @param os
     * @param cmd
     * @return
     * @throws IOException
     */
    private static String sendCommand(InputStream is, OutputStream os,
                                      String cmd) throws IOException {
        os.write(cmd.getBytes());
        os.flush();

        StringBuffer sb = new StringBuffer();
        int beat = 0;
        while (true) {
            if (beat > 3) {
                break;
            }

            if (is.available() > 0) {
                byte[] b = new byte[is.available()];
                is.read(b);
                sb.append(new String(b));
                beat = 0;
            } else {
                if (sb.length() > 0) {
                    beat++;
                }
                try {
                    Thread.sleep(sb.toString().trim().length() == 0 ? 1000 : 300);
                } catch (InterruptedException e) {
                }
            }
        }
        return sb.toString();
    }
}
